package com.knoya.chejian.pda.module.zupanchaxun

import android.app.ActivityManager
import android.app.AlertDialog
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.text.Editable
import android.util.Log
import android.view.View
import com.knoya.chejian.pda.R
import com.knoya.chejian.pda.activity.BaseActivity
import com.knoya.chejian.pda.minterface.OnUserDataInterface
import com.knoya.chejian.pda.myadapter.ArrayAdapter
import com.knoya.chejian.pda.myadapter.ZupanChaxunAdapter
import com.knoya.chejian.pda.util.JsonUtil
import com.knoya.chejian.pda.util.Myutil
import kotlinx.android.synthetic.main.activity_zupan_chaxun.*
import org.json.JSONException
import org.json.JSONObject
import com.knoya.chejian.pda.Myapp
import kotlinx.android.synthetic.main.header_knoya.*


class ZupanChaxunActivity : BaseActivity(), View.OnClickListener {

    val kehuleibie = ArrayList<String>()
    lateinit var pans : ArrayList<ZupanChaxunBean>
    lateinit var panadapter: ZupanChaxunAdapter
    lateinit var M : ZupanChakanM
    lateinit var dialog: AlertDialog
    override fun getLayoutId(): Int {
        when(jiemian){
            1 -> return R.layout.activity_zupan_chaxun
            2 -> return R.layout.activity_zupan_chaxun_2
        }
        return R.layout.activity_zupan_chaxun
    }

    override fun initCreate() {
        iv_header_left.visibility = View.VISIBLE
        iv_header_left.setOnClickListener(this)
        tv_header_title.text = "组盘查询"
        M = ZupanChakanM()
        kehuleibie.add("按订单")
        kehuleibie.add("按托盘")
        when(jiemian){
            1 -> {
                val adapter = ArrayAdapter(this, R.layout.lv_sp_tvitem, kehuleibie)
                Sp_Chaxun.adapter = adapter
            }
            2 ->{
                val adapter = ArrayAdapter(this, R.layout.lv_sp_tvitem_2, kehuleibie)
                Sp_Chaxun.adapter = adapter
            }
        }
        Bt_Chaxun.setOnClickListener(this)
        pans = ArrayList()
        panadapter = ZupanChaxunAdapter(pans,this)
        Lv_Chaxun.adapter = panadapter

        tv_header_title.isFocusable = true
        tv_header_title.isFocusableInTouchMode = true
        tv_header_title.requestFocus()
        tv_header_title.requestFocusFromTouch()

        mBoradcastReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                if(!isAPPBroughtToBackground()){
                    return
                }
                if (intent.action == "nlscan.action.SCANNER_RESULT" && intent.hasExtra("SCAN_BARCODE1")) {
                    val scanResult_1 = intent.getStringExtra("SCAN_BARCODE1").trim()
                    samiaoOk(scanResult_1)
                }
                if(intent.action == "android.intent.ACTION_DECODE_DATA" && intent.hasExtra("barcode_string")){
                    val scanResult = intent.getStringExtra("barcode_string").trim()
                    samiaoOk(scanResult)
                }
            }
        }
        Et_Chaxun.setOnEditorActionListener { _, actionId, _ ->
            var isOK = true
            isOK
        }
    }

    //扫描获取到数据后处理
    fun samiaoOk(data : String){
        Et_Chaxun.setText(data)
    }

    fun isAPPBroughtToBackground(): Boolean {
        val am = this.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val tasks = am.getRunningTasks(1)
        if (!tasks.isEmpty()) {
            val topActivity = tasks[0].topActivity
            if (topActivity.className == this.javaClass.name) {

                return true
            }
        }
        return false
    }

    override fun onClick(v: View?) {
        when(v){
            Bt_Chaxun -> {
                getdatahttp()
            }
            iv_header_left -> {
                finish()
            }
        }
    }

    fun getdatahttp(){
        var pallet_num = ""
        var pcode = ""
        if(Sp_Chaxun.selectedItem.toString() == "按订单"){
            pallet_num = ""
            pcode = Et_Chaxun.text.toString().trim()
        }else if(Sp_Chaxun.selectedItem.toString() == "按托盘"){
            pallet_num = Et_Chaxun.text.toString().trim()
            pcode = ""
        }
        if(pcode == "" && pallet_num == ""){
            Myutil.tishidialog(this,"录入条码或者托盘后才能查询")
            return
        }
        dialog = Myutil.showupdatedialog(this@ZupanChaxunActivity, "正在获取数据", false)
        M.getPanOnum(this,pallet_num,pcode,object : OnUserDataInterface {
            override fun onUserData(data: String?) {
                Log.d("onUserData",data)
                if(data == null){
                    return
                }
                jsondata(data)
            }

            override fun onNot(throwable: String?) {
            }

        })
    }

    fun jsondata(data : String){
        pans.clear()
        var status = ""
        var msg = ""
        try {
            var jo = JSONObject(data)
            status = JsonUtil.getvolue(jo,"status")
            var js = JsonUtil.getjsvolue(jo,"data")
            msg = JsonUtil.getvolue(jo ,"msg")
            for(i in 0 until js.length()){
                var palletjo = js[i] as JSONObject
                var bean = ZupanChaxunBean()
                bean.onum = JsonUtil.getvolue(palletjo,"onum")
                bean.intime = JsonUtil.getvolue(palletjo,"intime")
                bean.pallet_num = JsonUtil.getvolue(palletjo,"pallet_num")
                bean.position = JsonUtil.getvolue(palletjo,"position")
                bean.position_buffer = JsonUtil.getvolue(palletjo,"position_buffer")
                bean.zp_ctime = JsonUtil.getvolue(palletjo,"zp_ctime")
                pans.add(bean)
            }
        }catch (e : JSONException){
            e.printStackTrace()
        }
        if(status == "success"){
            panadapter.notifyDataSetChanged()
            if(pans.size == 0){
                Myutil.tishidialog(this@ZupanChaxunActivity, "没有找到包条码$data")
            }
        }else if(status == "error"){
            if(msg != ""){
                Myutil.tishidialog(this,msg)
            }
        }
        dialog.dismiss()
    }

}
